//
//  ViewController.m
//  19---JSON训练
//
//  Created by 冀永金 on 16/8/9.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "NewsCollectionCell.h"
#import "MyCollectionViewLayout.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MyCollectionViewLayoutDelegate>
@property (nonatomic, strong) NSMutableArray<NewsTitle *> *titleMary;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    MyCollectionViewLayout *title = (MyCollectionViewLayout *)self.myCollectionView.collectionViewLayout;
    title.delegate = self;
    self.myCollectionView.showsHorizontalScrollIndicator = NO;
    [self handleData];
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)handleData {
    NSString *path = [[NSBundle mainBundle]pathForResource:@"News" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *newsTitleDic = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error:&error];
    NSArray *list = newsTitleDic[@"tList"];
    self.titleMary = [NSMutableArray array];
    for (NSDictionary *dic in list) {
        NewsTitle *title = [NewsTitle newsWithDic:dic];
        [_titleMary addObject:title];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return  self.titleMary.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
    NewsTitle *title = self.titleMary[indexPath.row];
    [cell setTitle:title];
    return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitle *title = self.titleMary[indexPath.row];
    
    CGRect newRect = [title.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, self.myCollectionView.bounds.size.height) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    
    return ceilf(newRect.size.width);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
